//
//  UpdateUserInfoViewController.m
//  beautyLamp
//
//  Created by Tam Kwok To Michael on 2017/8/14.
//  Copyright © 2017年 Tam Kwok To Michael. All rights reserved.
//

#import "UpdateUserInfoViewController.h"
#import "UpdateUserInfoTableViewCell.h"
#import "UpdateUserNameViewController.h"
#import "UpdateSexViewController.h"
#import "UpdateSignViewController.h"
#import "User.h"
#import "BLHeader.h"
#import <MBProgressHUD.h>
#import "ImageUpload2Server.h"
#import "ManagerAddressViewController.h"
#import "UpdateUserHeadImgTableViewCell.h"
#define ReuserIndetify2 @"reuse2"
#import "UpdateAlipayAccountViewController.h"


@interface UpdateUserInfoViewController () <UITableViewDelegate, UITableViewDataSource, UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) NSDictionary *sectionTitle;
@property (nonatomic, strong) NSDictionary *sectionDetail;

@end

@implementation UpdateUserInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
}


- (void)setupUI {
    self.title = @"编辑资料";
    [self loadUserInfo];
    [self.tableView registerNib:[UINib nibWithNibName:@"UpdateUserInfoTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:ReuseIdentify];
    [self.tableView registerNib:[UINib nibWithNibName:@"UpdateUserHeadImgTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:ReuserIndetify2];
    self.tableView.tableFooterView = [UIView new];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
}


- (void) loadUserInfo {
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    [self dealWithData];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateNotification) name:UPDATEUISERINFONOTIFICATION object:nil];
}

- (void)updateNotification {
    [self dealWithData];
    [self.tableView reloadData];
}

- (void)dealWithData {
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    NSString *userIconUrl = [userDefault objectForKey:USERIMG];
    NSArray *sectionTitle1 = @[@"头像"];
    NSArray *sectionDetail1 = @[userIconUrl];
    
    NSString *userName = [userDefault objectForKey:USERNAME];
    NSString *tel = [userDefault objectForKey:USERTEL];
    NSArray *sectionTitle2 = @[@"用户名", @"电话"];
    NSArray *sectionDetail2 = @[userName, tel];
    
    NSString *theClass = [userDefault objectForKey:USERCLASS];
    NSString *userClass = [theClass integerValue] == 1 ?  @"店主" : @"销售";
    
    NSString *userAddress = [userDefault objectForKey:USERADDR] ? [userDefault objectForKey:USERADDR] : @" ";
    NSString *userSex = [userDefault objectForKey:USERSEX];
    
    if(userSex && [userSex integerValue] == 1) {// 1. 男 2 女
        userSex = @"男";
    }else if(userSex && [userSex integerValue] == 2) {
        userSex = @"女";
    }else {
        userSex = @" ";
    }
    NSArray *sectionTitle3 = @[ @"角色",@"性别", @"地址"];
    NSArray *sectionDetail3 = @[userClass, userSex, userAddress];
    
    NSString *sign = [userDefault objectForKey:USERSIGN] ? [userDefault objectForKey:USERSIGN] : @" ";
     NSString *AlipayAcount = [userDefault objectForKey:USERNUM] ? [userDefault objectForKey:USERNUM] : @" ";
    NSArray *sectionTitle4 = @[@"签名",@"支付宝账号"];
    NSArray *sectionDetail4 = @[sign, AlipayAcount];
    
    self.sectionTitle = @{@"0" : sectionTitle1, @"1" : sectionTitle2, @"2" : sectionTitle3, @"3" : sectionTitle4};
    self.sectionDetail = @{@"0" : sectionDetail1, @"1" : sectionDetail2, @"2" : sectionDetail3, @"3" : sectionDetail4};
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSArray *array = [self.sectionTitle objectForKey:[NSString stringWithFormat:@"%li",section]];
    return array.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        UpdateUserHeadImgTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ReuserIndetify2];
        NSArray *title = [self.sectionTitle objectForKey:[NSString stringWithFormat:@"%li",indexPath.section]];
        NSArray *detail = [self.sectionDetail objectForKey:[NSString stringWithFormat:@"%li",indexPath.section]];
        [cell setupUI:title[indexPath.row] imageURL:detail[indexPath.row]];
        return cell;
    }
    UpdateUserInfoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ReuseIdentify];
    NSArray *title = [self.sectionTitle objectForKey:[NSString stringWithFormat:@"%li",indexPath.section]];
    NSArray *detail = [self.sectionDetail objectForKey:[NSString stringWithFormat:@"%li",indexPath.section]];
    //NSLog(@"%@ - %@ ",detail, detail[indexPath.row]);
    [cell setupCell:title[indexPath.row] detailInfo:detail[indexPath.row]];
    return cell;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return @" ";
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    return 60;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if(indexPath.section == 0) {
        [self updateUserHead];
    }else if(indexPath.section == 1) {
        if(indexPath.row == 0) {
            UpdateUserNameViewController *controller = [[UpdateUserNameViewController alloc] init];
            [self.navigationController pushViewController:controller animated:YES];
        }
    }else if(indexPath.section == 2) {
        if(indexPath.row == 0) {
            [self showTip:@"角色不能修改的哦！"];
        }else if(indexPath.row == 1) {
            UpdateSexViewController *sexController = [[UpdateSexViewController alloc] init];
            [self.navigationController pushViewController:sexController animated:YES];
        }else if(indexPath.row == 2) {
            ManagerAddressViewController *addressController = [[ManagerAddressViewController alloc] init];
            [self.navigationController pushViewController:addressController animated:YES];
        }
    
    }else if (indexPath.section == 3) {
        if (indexPath.row == 0) {
            UpdateSignViewController *controller = [[UpdateSignViewController alloc] init];
            [self.navigationController pushViewController:controller animated:YES];
        }else {
            NSString *alipay = [[NSUserDefaults standardUserDefaults] objectForKey:USERNUM];
            if (alipay) {
                UpdateAlipayAccountViewController *controller = [[UpdateAlipayAccountViewController alloc] init];
                [self.navigationController pushViewController:controller animated:YES];
            }else {
                 [self showTip:@"已存在支付宝账号，现修改哦！"];
            }
        }
    }
}


- (void)updateUserHead {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"修改头像" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    __weak typeof (self) weakSelf = self;
    NSMutableAttributedString *hogan = [[NSMutableAttributedString alloc] initWithString:@"修改头像"];
    [hogan addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20] range:NSMakeRange(0, [[hogan string] length])];
    [alert setValue:hogan forKey:@"attributedTitle"];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    
    UIAlertAction *photo = [UIAlertAction actionWithTitle:@"从本地相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf openPhotoLibrary];
    }];
    
    [photo setValue:[UIColor blackColor] forKey:@"_titleTextColor"];
    [alert addAction:photo];
    
    UIAlertAction *takePhoto = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf openCamera];
    }];
    [takePhoto setValue:[UIColor blackColor] forKey:@"_titleTextColor"];
    [alert addAction:takePhoto];
    [self presentViewController:alert animated:YES completion:nil];
}


- (void)openCamera {
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.mode = MBProgressHUDModeIndeterminate;
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init];
        imagePicker.allowsEditing = YES;
        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        imagePicker.delegate = self;
        [self presentViewController:imagePicker animated:YES completion:^{
            [hud hideAnimated:YES];
        }];
    }
}

- (void)openPhotoLibrary {
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.mode = MBProgressHUDModeIndeterminate;
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]){
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init];
        imagePicker.allowsEditing = YES;
        imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        imagePicker.delegate = self;
        [self presentViewController:imagePicker animated:YES completion:^{
            [hud hideAnimated:YES];
        }];
    }
}


#pragma mark - UIImagePickerControllerDelegate
// 拍照完成回调
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(nullable NSDictionary<NSString *,id> *)editingInfo NS_DEPRECATED_IOS(2_0, 3_0){
    if (picker.sourceType == UIImagePickerControllerSourceTypeSavedPhotosAlbum) return;
    if(picker.sourceType == UIImagePickerControllerSourceTypeCamera){
        //图片存入相册
        UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
    }
    [self imagePostToServer:image];
    [self dismissViewControllerAnimated:YES completion:nil];
}


- (void)imagePostToServer:(UIImage *)image {
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.mode = MBProgressHUDModeIndeterminate;
    __weak typeof (self) weakSelf = self;
    [ImageUpload2Server postImage:image completer:^(id resultObject, NSError *error) {
        if(error) {
            hud.mode = MBProgressHUDModeText;
            hud.label.text = [error localizedDescription];
            [hud hideAnimated:YES afterDelay:3];
            return ;
        }
        [weakSelf.tableView reloadData];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"updateHeadView" object:image];
        [[NSNotificationCenter defaultCenter] postNotificationName:UPDATEUISERINFONOTIFICATION object:image];
        [hud hideAnimated:YES];
    }];
}

//进入拍摄页面点击取消按钮
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)showTip:(NSString *)tip {
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.mode = MBProgressHUDModeText;
    hud.label.text = tip;
    [hud hideAnimated:YES afterDelay:3];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self loadUserInfo];
    [self.tableView reloadData];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UPDATEUISERINFONOTIFICATION object:nil];
}
@end
